const mongoose = require('mongoose');

class SocketClientManager {
  constructor() {
    // 存储模块连接的Map
    this.connections = new Map();
    // 存储模块处理器的Map
    this.moduleHandlers = new Map();
    // 存储最后活跃时间的Map
    this.lastActiveTime = new Map();
    // 心跳超时时间(毫秒)
    this.heartbeatTimeout = 90000; // 90秒
    // 清理间隔(毫秒)
    this.cleanupInterval = 3600000; // 1小时

    // 启动定时清理
    this.startCleanupTimer();
  }

  // 注册模块处理器
  registerHandler(moduleType, handler) {
    this.moduleHandlers.set(moduleType, handler);
  }

  // 处理新的WebSocket连接
  handleConnection(connection, moduleType) {
    // 验证模块类型
    if (!this.moduleHandlers.has(moduleType)) {
      connection.send(JSON.stringify({
        type: 'error',
        code: 4001,
        reason: '模块未授权'
      }));
      connection.close();
      return;
    }

    // 存储连接
    this.connections.set(moduleType, connection);
    this.lastActiveTime.set(moduleType, Date.now());

    // 设置消息处理器
    connection.on('message', async (rawData) => {
      try {
        const data = JSON.parse(rawData.toString());
        this.lastActiveTime.set(moduleType, Date.now());

        // 处理心跳消息
        if (data.type === 'ping') {
          connection.send(JSON.stringify({ type: 'pong' }));
          return;
        }

        // 获取并执行模块处理器
        const handler = this.moduleHandlers.get(moduleType);
        if (handler) {
          const result = await handler(data);
          if (result) {
            connection.send(JSON.stringify(result));
          }
        }
      } catch (error) {
        console.error('消息处理错误:', error);
        connection.send(JSON.stringify({
          type: 'error',
          code: 500,
          module: moduleType,
          message: '消息处理失败'
        }));
      }
    });

    // 处理连接关闭
    connection.on('close', () => {
      this.connections.delete(moduleType);
      this.lastActiveTime.delete(moduleType);
    });
  }

  // 启动定时清理器
  startCleanupTimer() {
    setInterval(() => {
      const now = Date.now();
      for (const [moduleType, lastActive] of this.lastActiveTime.entries()) {
        if (now - lastActive > this.heartbeatTimeout) {
          const connection = this.connections.get(moduleType);
          if (connection) {
            connection.close();
            this.connections.delete(moduleType);
            this.lastActiveTime.delete(moduleType);
          }
        }
      }
    }, this.cleanupInterval);
  }

  // 向指定模块发送消息
  sendToModule(moduleType, message) {
    const connection = this.connections.get(moduleType);
    if (connection) {
      connection.send(JSON.stringify(message));
      return true;
    }
    return false;
  }
}

// 创建单例实例
const socketClientManager = new SocketClientManager();

module.exports = socketClientManager;